# 项目:
# 文件: tools
# 作者: Yang
# 日期: 2025/5/21 09:06
# coding:utf-8

import json
from time import sleep
import random
import os

from selenium.webdriver.support.select import Select
from selenium import webdriver

class UIAction:

    driver = None

    @classmethod
    def get_driver(cls):
        if cls.driver is None:   # 单例模式
            cls.driver = webdriver.Edge()
            cls.driver.implicitly_wait(5)  #隐式等待
            cls.driver.maximize_window()  #最大化窗口
        return cls.driver

    @classmethod
    def write(cls,element,value):   #登录页面账号密码，验证码方法
        element.click()
        element.clear()
        element.send_keys(value)

    @classmethod
    def is_element_present(cls, by, value):
        """
        判断某个元素是否存在，返回真或假的结果
        :param by: 定位方式
        :param value: 定位值
        :return: True or False
        """
        try:
            cls.driver.find_element(by, value)
            return True
        except Exception as e:
            return False

    @classmethod
    def select_random_first(cls,element):
        options_count = len(Select(element).options)
        random_index = random.randint(1, options_count - 1)
        Select(element).select_by_index(random_index)

    @classmethod
    def do_login(cls):
        driver = cls.driver
        login_info = Util.read_json('../data/conf.json')['login_info']
        driver.get('http://localhost:8080/YunDuanBoss/login')     #获取网址
        uname = driver.find_element('name', 'userName')       #找元素username(账户名)
        cls.write(uname, login_info['uname'])
        upass = driver.find_element('name', 'userPass')       #找元素password(密码)
        cls.write(upass, login_info['upass'])
        driver.find_element('css selector',                 #找按钮的selector
                            '#form-login > div > div > div.modal-footer > button').click()
        sleep(2)

class Assert:       #断言类

    @classmethod
    def assert_equal(cls,expect, actual):   #断言结果方法(相等方法)
        if expect == actual:                #期望与实际结果是否相等
            print('test pass')              #测试通过
        else:
            print('test fail')              #测试失败

    @classmethod
    def assert_not_equal(cls, expect, actual):  #断言结果方法(不等方法)
        if expect != actual:                    #期望与实际结果不相等
            print('test pass')                  #测试通过
        else:
            print('test fail')                  #测试失败

    @classmethod
    def assert_contain(cls,expect, actual):     #断言结果方法(包含方法)
        if actual in expect:                    #期望结果在实际结果里
            print('test pass')                  #测试通过
        else:
            print('test fail')                  #测试失败

class Util:

    # @classmethod
    # def read_txt(cls,path):
    #     with open(path,encoding='utf-8') as file:

    @classmethod
    def read_ini(cls,section):
        with open('../data/elements.ini',encoding='utf-8') as file:
            contents = file.read()
        all = contents.split('[ ')
        result = {}
        for item in all:
            if item.startswith(section):
                temp = item.split(' ]')[1].strip()
                items = temp.split('\n')
                for it in items:
                    if not it.startswith('# ') and it != '\n':
                        value = it.split(' = ')[1]
                        if '# ' in value:
                            value1 = value.split('# ')[0].strip()
                            result[it.split(' = ')[0]] = value1
                        else:
                            result[it.split(' = ')[0]] = value
                return result

    @classmethod
    def get_ini_value(cls,section,option):
        result = cls.read_ini(section)
        return eval(result[option])

    @classmethod
    def get_info(cls,casename):
        caseinfo = Util.read_json('../data/conf.json')[casename]
        return Util.read_excel(**caseinfo)

    # sheetname,starrow,endrow,data_col,expect_col
    @classmethod
    def read_excel(cls, **kwargs):
        import xlrd
        workbook = xlrd.open_workbook('../data/testsace.xls')
        sheet = workbook.sheet_by_name(kwargs['sheetname'])
        li = []
        for i in range(kwargs['starrow'], kwargs['endrow']):
            di = {}
            api_url = sheet.cell(i, kwargs['api_url']).value  # 读取第i列的api_url
            di['api_url'] = api_url
            api_method = sheet.cell(i, kwargs['api_method']).value
            di['api_method'] = api_method
            api_data = sheet.cell(i, kwargs['api_data']).value
            temp = str(api_data).split('\n')
            for t in temp:
                di[t.split('=')[0]] = t.split('=')[1]
            status_code = sheet.cell(i, kwargs['status_code']).value
            di['status_code'] = status_code
            resp_content = sheet.cell(i, kwargs['resp_content']).value
            di['resp_content'] = resp_content
            expect = sheet.cell(i, kwargs['expect']).value
            di['expect'] = expect
            li.append(di)
        return li


    @classmethod
    def read_json(cls, path):
        """
        用于读取指定的json文件，返回json格式的数据
        :param path: json文件的路径和名称
        :return: json格式的数据
        """
        with open(path, encoding='utf-8') as file:
            contents =  json.load(file)
        return contents

    @classmethod
    def get_conn(cls):
        import pymysql
        return pymysql.connect(host='localhost', user='root',
                               password='1234', database='woniusales', port=3306,charset='utf8')

    @classmethod
    def query(cls, sql):
        conn = cls.get_conn()
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result

    @classmethod
    def update(cls, sql):
        conn = cls.get_conn()
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        cursor.close()
        conn.close()


if __name__ == '__main__':

    print(Util.get_info('add_single_choice'))
